import { useState, useEffect } from "react"
import { useNavigate } from "react-router-dom"
import RoleSearch from "./roleSearch/index"
import { roleList, roleDelete, roleEdit } from "@/api/index"
import { Table, Button, Pagination, Tag, Space, message, Popconfirm } from "antd"
import dayjs from "dayjs"
import "./style.less"

const Role = () => {
  const navigate = useNavigate()
  const [page, setPage] = useState(1)
  const [limit, setLimit] = useState(5)
  const [total, setTotal] = useState(0)
  const [dataSource, setDataSource] = useState([])

  useEffect(() => {
    getRoleList({ page, limit })
  }, [])

  const columns = [
    {
      title: "创建时间",
      width: 100,
      dataIndex: "create_time",
      key: "create_time",
      fixed: "left",
      render: (time) => dayjs(time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      title: "角色名称",
      width: 100,
      dataIndex: "name",
      key: "name"
    },
    {
      title: "角色状态",
      width: 100,
      dataIndex: "state",
      key: "state",
      render: (text) =>
        text === 0 ? <Tag color="#87d068">启用</Tag> : <Tag color="#f50">禁用</Tag>
    },

    {
      title: "权限数量",
      dataIndex: "menu_id",
      key: "menu_id",
      width: 150,
      render: (num) => (num && num.length) || 0
    },
    {
      title: "修改时间",
      width: 200,
      dataIndex: "update_time",
      key: "update_time",
      render: (time) => dayjs(time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      title: "操作",
      key: "operation",
      fixed: "right",
      width: 140,
      render: (_, { _id, name, state }) =>
        name !== "超级管理员" && (
          <Space size={"small"}>
            <a onClick={() => onRoleActionClick("detail", _id)}>查看</a>
            <a onClick={() => onRoleActionClick("edit", _id)}>编辑</a>
            <Popconfirm
              title="是否改变状态"
              onConfirm={() => handleClick("update", _id, !state, Date.now())}
              okText="确定"
              cancelText="取消"
            >
              {state === 0 ? <a>禁用</a> : <a>启用</a>}
            </Popconfirm>
            <Popconfirm
              title="是否要删除"
              onConfirm={() => handleClick("delete", _id)}
              okText="确定"
              cancelText="取消"
            >
              {_id === "655efac3c81d468a83c29f86" ? "" : <a>删除</a>}
            </Popconfirm>
          </Space>
        )
    }
  ]

  const roleSearchColumns = [
    {
      label: "角色名称",
      name: "name",
      type: "input",
      placeholder: "请输入角色名称"
    },
    {
      label: "角色状态",
      name: "state",
      type: "select",
      placeholder: "请选择角色状态",
      options: [
        {
          title: "启用",
          value: 0
        },
        {
          title: "禁用",
          value: 1
        }
      ]
    }
  ]
  const getRoleList = async (value) => {
    const { pageData, total, page, limit } = await roleList(value)
    setLimit(limit)
    setPage(page)
    const data =
      (pageData &&
        pageData.map((item) => {
          return {
            ...item,
            key: item._id
          }
        })) ||
      []
    setTotal(() => total)
    setDataSource(() => data)
  }

  const onRoleActionClick = (type, _id = null) => {
    navigate(type !== "add" ? `/admin/role/${type}?_id=${_id}` : `/admin/role/add`)
  }

  const onSearchStateChange = (data) => {
    // 删除对象当中为空的值
    data = Object.fromEntries(Object.entries(data).filter((item) => item[1] !== undefined))
    console.log(data)
    getRoleList(data)
  }

  // 提示泡
  const handleClick = async (str, id, state, update_time) => {
    if (str === "delete") {
      const data = await roleDelete({ _id: id })
      if (data.code === 200) {
        getRoleList({ page, limit })
        message.success("删除成功")
      }
    } else if (str === "update") {
      // console.log(update_time)
      const data = await roleEdit({ _id: id, state, update_time })
      console.log(update_time)
      if (data.code === 200) {
        getRoleList({ page, limit })
        message.success("状态改变成功")
      }
    }
  }

  return (
    <div className="role-list" style={{ marginBottom: 56 }}>
      <div className="role-list-title">
        <h3>角色列表</h3>
      </div>
      <div>
        <RoleSearch columns={roleSearchColumns} onSearch={onSearchStateChange} page={page} />
      </div>
      <div style={{ padding: "24px 0px" }}>
        <Button type="primary" onClick={() => onRoleActionClick("add")}>
          新建
        </Button>
      </div>
      <div className="role-form-list">
        <Table
          // style={{ height: "335px" }}
          columns={columns}
          dataSource={dataSource || []}
          fixHeight={true}
          scroll={{
            x: 1500,
            y: 335
          }}
          pagination={false}
        />
      </div>
      <Pagination
        total={total}
        current={page}
        pageSize={limit}
        showQuickJumper
        onChange={(page, limit) => {
          getRoleList({ page, limit })
        }}
        pageSizeOptions={["2", "5", "10", "20"]}
        showSizeChanger
        onShowSizeChange={(page, limit) => {
          getRoleList({ page, limit })
        }}
        style={{
          marginTop: 24,
          float: "right"
        }}
        showTotal={(total) => `共 ${total} 条数据`}
      />
    </div>
  )
}
export default Role
